import 'package:dingtalk/core/model/message_item_model.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

String chatMessageRecordSql = "CREATE TABLE chat_message_record ("
    "id INTEGER PRIMARY KEY, "
    "chatId TEXT, "
    "userId TEXT, "
    "userName TEXT, "
    "chatName TEXT, "
    "message TEXT, "
    "messageType INTEGER, "
    "avatar TEXT, "
    "groupAvatars TEXT, "
    "time INTEGER, "
    "unReadCount INTEGER, "
    "isSingle INTEGER, "
    "isGroup INTEGER, "
    "isDisturbing INTEGER, "
    "isSpecialAttention INTEGER, "
    "isAtYou INTEGER, "
    "isAtAll INTEGER, "
    "isStick INTEGER"
    ")";

class ChatMessageRecordProvider {
  factory ChatMessageRecordProvider() => _getInstance();

  static ChatMessageRecordProvider get instance => _getInstance();

  static ChatMessageRecordProvider _instance;

  static String _dbName = 'flutter_dingtalk.db';

  Database _database;

  ChatMessageRecordProvider._internal();

  static ChatMessageRecordProvider _getInstance() {
    if (_instance == null) {
      _instance = ChatMessageRecordProvider._internal();
    }
    return _instance;
  }

  Future<void> _openDB() async {
    // await deleteDatabase(join(await getDatabasesPath(), _dbName));
    if (_database == null) {
      _database = await openDatabase(join(await getDatabasesPath(), _dbName),
          version: 1, onConfigure: (Database db) {},
          onCreate: (Database db, int version) async {
        await db.execute(chatMessageRecordSql);
        print("onCreate ${db.runtimeType} $version ");
      }, onOpen: (Database db) {
        print("onOpen ${db.runtimeType}");
      }, onDowngrade: (Database db, int oldVersion, int newVersion) {
        print("onDowngrade ${db.runtimeType} $oldVersion $newVersion");
      }, onUpgrade: (Database db, int oldVersion, int newVersion) {
        print("onUpgrade ${db.runtimeType} $oldVersion $newVersion");
      });
    }
  }

  Future<void> saveChatMessageRecord(THMessageItemModel model) async {
    await _openDB();
    await _database?.insert('chat_message_record', model.toJson(),
        conflictAlgorithm: ConflictAlgorithm.replace);
  }

  Future<List<THMessageItemModel>> queryChatMessageRecord() async {
    await _openDB();
    List<Map<String, dynamic>> maps =
        await _database?.query('chat_message_record');
    if (maps != null && maps.length > 0) {
      return List.generate(maps.length, (i) {
        THMessageItemModel model = THMessageItemModel(
            chatId: maps[i]['chatId'],
            userId: maps[i]['userId'],
            message: maps[i]['message'],
            chatName: maps[i]['chatName'],
            userName: maps[i]['userName'],
            messageType: maps[i]['messageType'],
            time: maps[i]['time'],
            unReadCount: maps[i]['unReadCount'],
            isSingle: maps[i]['isSingle'],
            avatar: maps[i]['avatar'],
            isGroup: maps[i]['isGroup'],
            groupAvatars: maps[i]['groupAvatars'],
            isDisturbing: maps[i]['isDisturbing'],
            isSpecialAttention: maps[i]['isSpecialAttention'],
            isAtYou: maps[i]['isAtYou'],
            isAtAll: maps[i]['isAtAll'],
            isStick: maps[i]['isStick']);
        return model;
      });
    }
    return [];
  }
}
